//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package cn.ekuma.epos.qkorder.orderbag.shared;

import cn.ekuma.epos.bean.util.erp.OrderHelper;
import cn.ekuma.epos.businesslogic.RoleUtil;
import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import com.openbravo.pos.base.AppView;

import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.order.JOrdersFinder;
import cn.ekuma.epos.order.JSharedLinkOrdersFinder;
import cn.ekuma.epos.order.JSharedOrdersFinder;
import cn.ekuma.epos.qkorder.dialog.JOrderAnalysisDialog;
import cn.ekuma.epos.qkorder.dialog.JOrderTypeDialog;
import cn.ekuma.epos.qkorder.JOrdersBag;
import cn.ekuma.epos.qkorder.OrdersEditor;

import com.openbravo.bean.AppUser;
import com.openbravo.bean.BusinessPartner;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.sales.TaxesException;
import com.openbravo.bean.erp.Order;
import java.util.*;
import javax.swing.*;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.bean.infobean.CustomerInfo;
import com.openbravo.bean.erp.viewbean.FindOrdersInfo;
import com.openbravo.bean.Location;
import com.openbravo.bean.erp.OrderState;
import com.openbravo.bean.erp.OrderType;
import com.openbravo.bean.shard.UserOrderTypePermission;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;


public class JOrdersBagShared extends JOrdersBag {
    
    private String m_sCurrentOrder = null;
    private I_DataLogicReceipts dlReceipts = null;
    private I_DataLogicCustomers dlCustomer=null;
    private I_DataLogicSystem dlSystem;
    private boolean editable;
	private JButton jFindLinkOrder;
	private JButton jInsertLinkOrder;

    /** Creates new form JOrdersBagShared */
    public JOrdersBagShared(AppView app, OrdersEditor panelOrder,I_DataLogicERP m_dlSales,I_DataLogicReceipts dlReceipts,I_DataLogicCustomers dlCustomer,I_DataLogicSystem dlSystem) {
        
        super(app, panelOrder, m_dlSales);
        
        this.dlReceipts = dlReceipts;
        this.dlSystem = dlSystem;
        dlCustomer=panelOrder.getDlCustomers();
        initComponents();
        editable=true;

        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0);
        ActionListener actionListener = new ActionListener() {

         @Override
        public void actionPerformed(ActionEvent actionEvent) {
                m_jListOrdersActionPerformed(null);
           }
        };
        registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0);
        actionListener = new ActionListener() {

         @Override
        public void actionPerformed(ActionEvent actionEvent) {
                m_jDelOrderActionPerformed(null);
           }
        };
        registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        stroke = KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0);
        actionListener = new ActionListener() {

         @Override
        public void actionPerformed(ActionEvent actionEvent) {
                m_jNewOrderActionPerformed(null);
           }
        };
        registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
    
    public void activate() {
        
        // precondicion es que no tenemos Order activado ni Order en el panel
        
        m_sCurrentOrder = null;
        selectValidOrder();
        
        // Authorization
        //m_jDelOrder.setEnabled(m_App.getAppUserView().getUser().hasPermission("com.openbravo.pos.sales.JPanelOrderEdits"));
       
        // postcondicion es que tenemos Order activado aqui y Order en el panel
    }
    
    public boolean deactivate() {
        
        // precondicion es que tenemos Order activado aqui y Order en el panel
      if(this.editable)
         saveAndUnLockedCurrentOrder();
        
        m_sCurrentOrder = null;
        //m_panelOrder.setActiveOrder(null, null,false);
        return true;
        
        // postcondicion es que no tenemos Order activado ni Order en el panel
    }
        
    public void deleteOrder() {
        try {
             dlReceipts.deleteSharedOrder(m_sCurrentOrder);
             m_sCurrentOrder = null;
             selectValidOrder();
        } catch (BasicException ex) {
            MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), ex);
            msg.show(this);
        }
    }
    
    
    public void flushOrder() {
    	try {
            dlReceipts.deleteSharedOrder(m_sCurrentOrder);
            m_sCurrentOrder = null;
            setOrderEditAble(false);
       } catch (BasicException ex) {
           MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), ex);
           msg.show(this);
       }
    }
    
    public JComponent getBagComponent() {
        return this;
    }
    
    public JComponent getNullComponent() {
        return new JPanel();
    }
   
    private void saveCurrentOrder() {  
        // save current Order, if exists,
         if (m_sCurrentOrder != null) {
            try {
                dlReceipts.updateSharedOrder(m_sCurrentOrder, m_panelOrder.getReCalcActiveOrder(),m_App.getAppUserView().getUser().getId());
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                 msg.show(this);
            } catch (TaxesException e) {
            	 MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
                 msg.show(this);
			}
        }
    }

    private void saveAndUnLockedCurrentOrder(){
        if (m_sCurrentOrder != null) {
            try {
                dlReceipts.updateSharedOrderAndUnLocked(m_sCurrentOrder,m_panelOrder.getReCalcActiveOrder());
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                msg.show(this);
            } catch (TaxesException e) {
            	 MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
                 msg.show(this);
			}
        }
    }

    private void insertAndLockedShardOrder(Order newOrder){
        if (m_sCurrentOrder != null) {
            try {
                dlReceipts.insertSharedOrder(m_sCurrentOrder, newOrder);
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                 msg.show(this);
            }
        }
    }
    
    public void setActiveOrder(Order order,boolean isEditAble) throws BasicException{
    	if(editable)
            saveAndUnLockedCurrentOrder();
        if(isEditAble){
    	    	m_sCurrentOrder = order.getId();
    	    	dlReceipts.setSharedOrderLocked(m_sCurrentOrder,true,m_App.getAppUserView().getUser().getId());
        } else 
        	m_sCurrentOrder=null;
          m_panelOrder.setActiveOrder(order, null,isEditAble);
         setOrderEditAble(isEditAble);
        // END TRANSACTION                 
    }
    
    
    private void setActiveOrder(String id) throws BasicException{
        
        // BEGIN TRANSACTION
        Order Order = dlReceipts.getSharedOrder(id);
        if (Order == null)  {
            // Does not exists ???
            throw new BasicException(AppLocal.getIntString("message.noOrder"));
        } else {
            dlReceipts.setSharedOrderLocked(id,true,m_App.getAppUserView().getUser().getId());
            m_sCurrentOrder = id;
            m_panelOrder.setActiveOrder(Order, null,true);
            setOrderEditAble(true);
        } 
        // END TRANSACTION                 
    }
    
    private void selectValidOrder() {
		if (m_App.isCustomerView())
			newOrder();
		else {
			try {
				List<String> l = dlReceipts.getSharedOrderList();
				if (l.size() == 0) {
					newOrder();
				} else {
					setActiveOrder(l.get(0));
				}
			} catch (BasicException e) {
				new MessageInf(e).show(this);
				newOrder();
			}
		}
    }    
    
    @Override
    public void newOrder() {
    	newOrder(null);
    }
    
	@Override
	public void newOrder(CustomerInfo obj) {
		 JOrderTypeDialog orderTypeDialog=JOrderTypeDialog.getDialog(this);
	        try {
	            orderTypeDialog.init(m_App,obj, m_dlSales, dlCustomer);
	            orderTypeDialog.setVisible(true);
	        } catch (BasicException ex) {
	             MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotSetupOrderType"), ex);
	             msg.show(this);
	        }
	        if(orderTypeDialog.isOk()){
	            Order order = new Order();
	            order.setDate(orderTypeDialog.getCreateDate());
	            order.setID(UUID.randomUUID().toString());
	            order.setOrderId(OrderHelper.generateOrderId());
	            order.setDefineType(orderTypeDialog.getoType());
	            order.setOrderType(orderTypeDialog.getOrderType());
	            order.setUser(m_App.getAppUserView().getUser().getUserInfo());
	            CustomerInfo customerInfo=orderTypeDialog.getCustomerInfo();
	            if(order.getDefineType().isProductConsult()){
	                order.setConsultProductId(orderTypeDialog.getProdcutID());
	                order.setConsultProductAttsetinstid(orderTypeDialog.getProductInstDescID());
	                order.setConsultProductName(orderTypeDialog.getProdcutName());
	            }
	            try {
	            order.setCustomer((BusinessPartner) (customerInfo == null ? null : m_dlSales.findByStringId(BusinessPartner.class, customerInfo.getId())));
	             } catch (BasicException e) {
	               MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindcustomer"), e);
	               msg.show(this);
	            }
	            Location location=orderTypeDialog.getoLocateion();
	            if(location!=null){
	                 order.setLocationRef(location.getID());
	                 order.setLocationDesc(location.printName());
	                 order.setDeliverType(orderTypeDialog.getDeliverType());
	                 order.setDeliverTypeDesc(orderTypeDialog.getDeliverTypeDesc());
	            }
	            location=orderTypeDialog.getoLocateion1();
	            if(location!=null){
	                 order.setLocationRef1(location.getID());
	                 order.setLocationDesc1(location.printName());
	            }
	            if(order.getDefineType().getConsultType()==OrderType.CONSULTTYPE_Order||order.getDefineType().getConsultType()==OrderType.CONSULTTYPE_TimeSliceStore)
	                 order.setConsultRef(orderTypeDialog.getConsultID());
	            order.setReference_User(orderTypeDialog.getReferencePerson());
	            order.addState(new OrderState(m_App.getAppUserView().getUser().getUserInfo(),AppLocal.getIntString(OrderState.ORDERSTATE_Start)));
	            order.setCustomerAddr(orderTypeDialog.getCustomerAddr());
	            saveAndUnLockedCurrentOrder();
	            m_sCurrentOrder =order.getId();
	            insertAndLockedShardOrder(order); 
	            m_panelOrder.setActiveOrder(order, null,true);
	            setOrderEditAble(true);
	            return;
	          }
	        if(m_sCurrentOrder == null){
	            m_panelOrder.setActiveOrder(null, null,false);
	        }
		
	}
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        m_jNewOrder = new javax.swing.JButton();
        m_jDelOrder = new javax.swing.JButton();
        jSaveOrder = new javax.swing.JButton();
        m_jListOrders = new javax.swing.JButton();
        jImpOrder = new javax.swing.JButton();
        jAnalysis = new javax.swing.JButton();
        jFindOldOrder = new javax.swing.JButton();
        jReEdit = new javax.swing.JButton();
        jRecordOrder = new javax.swing.JButton();
        jFindLinkOrder=new javax.swing.JButton();
        jInsertLinkOrder=new javax.swing.JButton();
        
        setLayout(new java.awt.BorderLayout());

        m_jNewOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editnew.png"))); // NOI18N
        m_jNewOrder.setFocusPainted(false);
        m_jNewOrder.setFocusable(false);
        m_jNewOrder.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jNewOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        m_jNewOrder.setRequestFocusEnabled(false);
        m_jNewOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jNewOrderActionPerformed(evt);
            }
        });
        jPanel1.add(m_jNewOrder);

        m_jDelOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editdelete.png"))); // NOI18N
        m_jDelOrder.setFocusable(false);
        m_jDelOrder.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jDelOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        m_jDelOrder.setRequestFocusEnabled(false);
        m_jDelOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jDelOrderActionPerformed(evt);
            }
        });
        jPanel1.add(m_jDelOrder);

        jSaveOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/filesave.png"))); // NOI18N
        jSaveOrder.setFocusable(false);
        jSaveOrder.setMaximumSize(new java.awt.Dimension(35, 25));
        jSaveOrder.setMinimumSize(new java.awt.Dimension(35, 25));
        jSaveOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jSaveOrder.setRequestFocusEnabled(false);
        jSaveOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jSaveOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jSaveOrder);

        m_jListOrders.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/unsortedList.png"))); // NOI18N
        m_jListOrders.setFocusPainted(false);
        m_jListOrders.setFocusable(false);
        m_jListOrders.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jListOrders.setPreferredSize(new java.awt.Dimension(35, 25));
        m_jListOrders.setRequestFocusEnabled(false);
        m_jListOrders.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jListOrdersActionPerformed(evt);
            }
        });
        jPanel1.add(m_jListOrders);

        jImpOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/redo16.png"))); // NOI18N
        jImpOrder.setFocusable(false);
        jImpOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jImpOrder.setRequestFocusEnabled(false);
        jImpOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jImpOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jImpOrder);

        jAnalysis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/cakes3d.png"))); // NOI18N
        jAnalysis.setFocusable(false);
        jAnalysis.setPreferredSize(new java.awt.Dimension(35, 25));
        jAnalysis.setRequestFocusEnabled(false);
        jAnalysis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAnalysisActionPerformed(evt);
            }
        });
        jPanel1.add(jAnalysis);

        jFindOldOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/search.png"))); // NOI18N
        jFindOldOrder.setFocusable(false);
        jFindOldOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jFindOldOrder.setRequestFocusEnabled(false);
        jFindOldOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFindOldOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jFindOldOrder);

        jReEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/edit.png"))); // NOI18N
        jReEdit.setFocusable(false);
        jReEdit.setPreferredSize(new java.awt.Dimension(35, 25));
        jReEdit.setRequestFocusEnabled(false);
        jReEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jReEditActionPerformed(evt);
            }
        });
        jPanel1.add(jReEdit);

        jRecordOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/greenled.png"))); // NOI18N
        jRecordOrder.setFocusable(false);
        jRecordOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jRecordOrder.setRequestFocusEnabled(false);
        jRecordOrder.setVerifyInputWhenFocusTarget(false);
        jRecordOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRecordOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jRecordOrder);

        jFindLinkOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/search.png"))); // NOI18N
        jFindLinkOrder.setFocusable(false);
        jFindLinkOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jFindLinkOrder.setRequestFocusEnabled(false);
        jFindLinkOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFindLinkOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jFindLinkOrder);
        
        jInsertLinkOrder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/filesave.png"))); // NOI18N
        jInsertLinkOrder.setFocusable(false);
        jInsertLinkOrder.setPreferredSize(new java.awt.Dimension(35, 25));
        jInsertLinkOrder.setRequestFocusEnabled(false);
        jInsertLinkOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jInsertLinkOrderActionPerformed(evt);
            }
        });
        jPanel1.add(jInsertLinkOrder);
        
        add(jPanel1, java.awt.BorderLayout.WEST);
    }// </editor-fold>//GEN-END:initComponents

	protected void jInsertLinkOrderActionPerformed(ActionEvent evt) {
		if (m_sCurrentOrder != null) {
            try {
                dlReceipts.insertLinkSharedOrder(m_sCurrentOrder, m_panelOrder.getActiveOrder());
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                 msg.show(this);
            }
        }
	}

	protected void jFindLinkOrderActionPerformed(ActionEvent evt) {
		JSharedLinkOrdersFinder finder= JSharedLinkOrdersFinder.getLinkOrderFinder(this, m_App, dlReceipts, m_dlSales, dlCustomer);
	       finder.setVisible(true);
	       FindOrdersInfo selectedOrder=finder.getSelectedOrder();
	       if(selectedOrder!=null){
	           String id=selectedOrder.getOrderId();
	           Order order = null;
	            try {
	                order = m_dlSales.loadLinkOrder(id);
	            } catch (BasicException ex) {
	                 MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotLoadOrder"),ex);
	                 msg.show(this);
	                 order=null;
	            }
	            if (order != null)  {
	            	try {
						setActiveOrder(order,false);
					} catch (BasicException e) {
						MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotLoadOrder"),e);
		                msg.show(this);
					}
	         }
	       }
	}

	public void m_jListOrder(){
       if(m_jListOrders.isEnabled())
          m_jListOrdersActionPerformed(null);
    }

    private void m_jListOrdersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jListOrdersActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {             
                try {
                    JSharedOrdersFinder orderFinder=JSharedOrdersFinder.getOrderFinder(JOrdersBagShared.this, m_App, dlReceipts, m_dlSales, dlCustomer);
                    orderFinder.setVisible(true);
                    FindOrdersInfo findOrder=orderFinder.getSelectedOrder();
                    if (findOrder != null) {
                        saveAndUnLockedCurrentOrder();
                        setActiveOrder(findOrder.getId());
                    }
                } catch (BasicException e) {
                    new MessageInf(e).show(JOrdersBagShared.this);
                    newOrder();
                }                    
            }
        }); 
    }//GEN-LAST:event_m_jListOrdersActionPerformed

    private void m_jDelOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDelOrderActionPerformed
        if(!RoleUtil.hasOrderTypePermission((AppUser) m_App.getAppUserView().getUser(),m_panelOrder.getActiveOrder().getDefineType().getId(), RoleUtil.getLocalePermissionName(UserOrderTypePermission.ORDERTYPEEVENT_Delete))){
            new MessageInf(MessageInf.SGN_NOTICE,AppLocal.getIntString("message.userPermissionNoGranted")).show(JOrdersBagShared.this);
            return ;
        }
        int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.wannadelete"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res == JOptionPane.YES_OPTION) {
            deleteOrder();
        }
        
    }//GEN-LAST:event_m_jDelOrderActionPerformed

    private void m_jNewOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jNewOrderActionPerformed
        newOrder();
    }//GEN-LAST:event_m_jNewOrderActionPerformed

    private void jSaveOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSaveOrderActionPerformed
        saveCurrentOrder();
    }//GEN-LAST:event_jSaveOrderActionPerformed

    private void jFindOldOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFindOldOrderActionPerformed
       JOrdersFinder finder= JOrdersFinder.getOrderFinder(this, m_App, m_dlSales, dlCustomer);
       finder.setVisible(true);
       FindOrdersInfo selectedOrder=finder.getSelectedOrder();
       if(selectedOrder!=null){
           String id=selectedOrder.getOrderId();
           Order order = null;
            try {
                order = m_dlSales.loadOrder(id);
            } catch (BasicException ex) {
                 MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotLoadOrder"),ex);
                 msg.show(this);
                 order=null;
            }
            if (order != null)  {
            	try {
					setActiveOrder(order,false);
				} catch (BasicException e) {
					MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotLoadOrder"),e);
	                msg.show(this);
				}
         }
       }
    }//GEN-LAST:event_jFindOldOrderActionPerformed

    private void jImpOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jImpOrderActionPerformed
          try {
                    JSharedOrdersFinder orderFinder=JSharedOrdersFinder.getOrderFinder(JOrdersBagShared.this, m_App, dlReceipts, m_dlSales, dlCustomer);
                    orderFinder.setVisible(true);
                    FindOrdersInfo findOrder=orderFinder.getSelectedOrder();
                    if (findOrder != null) {
                         Order order = dlReceipts.getSharedOrder(findOrder.getId());
                          if (order != null)  {
                              m_panelOrder.addOrderLines(order.getLines());
                         }
                    }
                } catch (BasicException e) {
                     new MessageInf(e).show(JOrdersBagShared.this);
              }

    }//GEN-LAST:event_jImpOrderActionPerformed

    private void jReEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jReEditActionPerformed
         try{
                    Order order = m_panelOrder.getActiveOrder();
                    m_dlSales.deleteOrder(order);
                    m_sCurrentOrder = order.getId(); // m_fmtid.format(Order.getId());
                    insertAndLockedShardOrder(order);
                    m_panelOrder.setActiveOrder(order, null, true);
                    setOrderEditAble(true);
                } catch (BasicException ex) {
                    new MessageInf(ex).show(JOrdersBagShared.this);
                }
            
    }//GEN-LAST:event_jReEditActionPerformed

    private void jAnalysisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAnalysisActionPerformed
       JOrderAnalysisDialog  analysisDlg = JOrderAnalysisDialog.newJDialog((Component)this, m_App, m_panelOrder.getActiveOrder(), m_dlSales, dlCustomer, dlReceipts, dlSystem);
       analysisDlg.setVisible(true);
    }//GEN-LAST:event_jAnalysisActionPerformed

    private void jRecordOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRecordOrderActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jRecordOrderActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jAnalysis;
    private javax.swing.JButton jFindOldOrder;
    private javax.swing.JButton jImpOrder;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jReEdit;
    private javax.swing.JButton jRecordOrder;
    private javax.swing.JButton jSaveOrder;
    private javax.swing.JButton m_jDelOrder;
    private javax.swing.JButton m_jListOrders;
    private javax.swing.JButton m_jNewOrder;
    // End of variables declaration//GEN-END:variables


    public void  setOrderEditAble(boolean editAble){
       m_jDelOrder.setEnabled(editAble);
       jSaveOrder.setEnabled(editAble);
       jImpOrder.setEnabled(editAble);
       if(m_App.isCustomerView())
    	   jReEdit.setEnabled(false);
       else
           jReEdit.setEnabled(!editAble);
       editable=editAble;
    }
}
